
<?php

class AuthController extends Zend_Controller_Action {

    public function init() {
        /* Initialize action controller here */
        $userdata = new Zend_Session_Namespace('userdata');
        if (isset($userdata->userdata)) {
            //mina
            //if is alerady login redirct user to index page
            //  $this->_helper->redirector('index', 'index');
            if ($this->_request->isXmlHttpRequest()) {

                $this->_helper->viewRenderer->setNoRender();
                $this->_helper->layout()->disableLayout();
            }
        }
    }

    public function indexAction() {
        $form = new Application_Form_Login();
        $request = $this->getRequest();
        if ($request->isPost()) {
            if ($form->isValid($request->getPost())) {
                $login = new Zend_Session_Namespace('login');
                $fullUrl = 'Location: ' . $login->url;
                if ($this->_process($form->getValues())) {
                    // We're authenticated! Redirect to the home page
                    //$this->_helper->redirector('index', 'index');
                    // We're authenticated! Redirect to the home page
                    //$this->_helper->redirector('index', 'index');
                    //$fullUrl = $this->view->url();

                    $login->username = $request->getParam('username');
                    $itemsNo = new Zend_Session_Namespace('itemsNo');
                    $itemsNo->itemsNo = 0;
                    $db = Zend_Db_Table_Abstract::getDefaultAdapter();
                    $uid = $db->select()->from('users')->where("username=?", $login->username);
                    $s = $db->fetchAll($uid);
                    $login->userObj = $s;
                    //echo $this->view->url();
                    if ($login->userObj[0]['role'] != "administrator") {
                        if ($fullUrl != '/shopflowers/public/auth') {

                            //$this->_redirect($fullUrl);
                            header($fullUrl);
                        } else {
                            header('Location: /shopflowers/public/index/index');
                        }
                    } else {
                        header('Location: /shopflowers/public/admin/productindex');
                    }
                } else {
                    header($fullUrl);
                }
            }
        }


        //mina
        if ($request->getParam('ajax') == 'yes') {      //that is mean this action reqeast by ajax
            $this->_helper->layout->disableLayout();
        }
        $this->view->form = $form;
        echo "<br><br><br>";
        /*
          $db = new Zend_Db_Adapter_Pdo_Mysql(array(
          'host' => '127.0.0.1',
          'username' => 'root',
          'password' => '',
          'dbname' => 'flowers'
          ));
          $select = $db->select()
          ->from('users');
          //mina

          //that is mean this action reqeast by ajax
          if ($request->getParam('ajax')=="yes") {
          $this->_helper->layout->disableLayout();
          }
          $this->view->form = $form;
          /*
          $db = new Zend_Db_Adapter_Pdo_Mysql(array(
          'host' => '127.0.0.1',
          'username' => 'root',
          'password' => '',
          'dbname' => 'flowers'
          ));
          $select = $db->select()
          ->from('users');
          >>>>>>> .r33

          $stmt = $db->query($select);

          $result = $stmt->fetchAll();
          //print_r($db);
         *
         */
    }

    protected function _process($values) {
        // Get our authentication adapter and check credentials
        $adapter = $this->_getAuthAdapter();

        $adapter->setIdentity($values['username']);
        $adapter->setCredential($values['password']);
        //print_r($adapter);
        $auth = Zend_Auth::getInstance();
        //print_r($auth);
        $result = $auth->authenticate($adapter);
        //print_r($result);

        if ($result->isValid()) {
            $user = $adapter->getResultRowObject();
            $auth->getStorage()->write($user);
            //mina
            //put user object in session
            //if ($user->status == "enable") {
            //$userdata = new Zend_Session_Namespace('data');
            //$userdata->userdata = $user;
            return true;
            //}
        }

        return false;
    }

    protected function _getAuthAdapter() {


        $db = Zend_Db_Table::getDefaultAdapter();
        $authAdapter = new Zend_Auth_Adapter_DbTable($db);

        $authAdapter->setTableName('users')
                ->setIdentityColumn('username')
                ->setCredentialColumn('password')
                ->setCredentialTreatment('SHA1(CONCAT(?,token))');
        return $authAdapter;
    }

    public function logoutAction() {
        //destroy session
        $login = new Zend_Session_Namespace('login');
        unset($login->userObj);
        $userdata = new Zend_Session_Namespace('userdata');
        unset($userdata->userdata);
        $myProducts = new Zend_Session_Namespace('products');
        unset($myProducts->id);
        $myProducts = new Zend_Session_Namespace('itemsNo');
        unset($myProducts->itemsNo);
        Zend_Auth::getInstance()->clearIdentity();
        $this->_helper->redirector('index'); // back to login page
    }

    public function contregAction() { // ammar
    }

    public function verifyAction() { // ammar
        $users = new Application_Model_User();
        $token = $this->getRequest()->getParam("tok");
        $email = $this->getRequest()->getParam("email");
        $x=$users->Verify($token, $email);  
    }

    public function signupAction() { // ammar
        $users = new Application_Model_User();
        $form = new Application_Form_Registeration();
        $this->view->form = $form;
        if ($this->getRequest()->isPost()) {
            if ($form->isValid($_POST)) {
                $data = $form->getValues();
                if ($data['password'] != $data['confirmPassword']) { // password correct
                    $this->view->errorMessage = "Password and confirm password don't match.";
                    return;
                }
                if ($users->checkUnique($data['username'])) { // username is unique?
                    $this->view->errorMessage = "Name already taken. Please choose another one.";
                    return;
                }
                $data['date_created'] = date("Y-m-d h:i:s");
                $data['token'] = rand(100, 1000);
                $data['token'] = sha1($data['token']);
                $data['password'] = SHA1($data['password'] . $data['token']);
                unset($data['confirmPassword']);
                $users->insert($data);
                // sending email to user for activation
                $smtpOptions = array(
                    'auth' => 'login',
                    'username' => 'zend900@gmail.com',
                    'password' => '0109404527',
                    'ssl' => 'ssl',
                    'port' => 465
                );
                $mailTransport = new Zend_Mail_Transport_Smtp('smtp.gmail.com', $smtpOptions);
                $email = new Zend_Mail();
                $email->addTo($data['email'])  // user's email
                        ->setFrom('zend900@gmail.com')
                        ->setSubject('ShopFlowers Registeration')
                        ->setBodyText("Welcome to our shopFlowers!
                        You, or someone using your email address, has completed registration at shopFlowers.com.
                        You can complete registration by clicking the following link:
                        http://localhost/shopflowers/public/auth/verify/tok/$data[token]/email/$data[email]
                        Please don't reply on this email.
                        If there is any error, please send us an email at zend900@gmail.com
                        Regards,
                        Shop Flowers Team "); // link with token or actication key
                $sent = true;
                try { // sending email
                    $email->send($mailTransport);
                } catch (Exception $e) {
                    $sent = false;
                }
                if ($sent) { // check for receiving mail
                    $this->_redirect("auth/contreg");
                } else {
                    //Mail failed to send.
                    $this->_redirect('auth/signup');
                }// end of else
            }// end of if(form is valid)
        }// end of if (get request is post)
    }

// end of function signup
}

// end of class

